//
//  BatchElor.m
//  BatchElor
//
//  Created by Luke van der Hoeven on 1/15/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "BatchElor.h"
#import "BatchController.h"

@implementation BatchElor

@synthesize outDir;

NSURLResponse *downloadResponse;
int cnt=0;
int bytesReceived = 0;

-(void) downloadFiles:sender filePath:(NSString *)file {
	NSURLRequest *requestFile = [NSURLRequest requestWithURL:[NSURL URLWithString:file]
													cachePolicy:NSURLRequestUseProtocolCachePolicy
												timeoutInterval:60.0];
	NSURLDownload *downloadFile = [[NSURLDownload alloc] initWithRequest:requestFile delegate:self];
	NSURLResponse *response = [[NSURLResponse alloc] initWithURL:[NSURL URLWithString:file] MIMEType:@"video/x-flv" expectedContentLength:-1 textEncodingName:nil];
	[self setDownloadResponse:response];
	
	if (downloadFile) {
	   // set the destination file now
	   NSString *path = [NSString stringWithFormat:@"%@/%@_%d.flv", outDir, @"video", cnt+=1];
	   [downloadFile setDestination:path allowOverwrite:YES];
	} else {
		NSLog(@"Problem downloading file.");
	}	
	
}

- (void)download:(NSURLDownload *)download didFailWithError:(NSError *)error {
	// release the connection
	[download release];

	// inform the user
	NSLog(@"Download failed! Error - %@ %@",
	   [error localizedDescription],
	   [[error userInfo] objectForKey:NSErrorFailingURLStringKey]);
}

- (void)downloadDidFinish:(NSURLDownload *)download {
	// release the connection
	[download release];

	// do something with the data
	NSLog(@"%@",@"downloadDidFinish");
}
		 
-(void)setDownloadResponse:(NSURLResponse *)aDownloadResponse {
    [aDownloadResponse retain];
	[downloadResponse release];
	downloadResponse = aDownloadResponse;
}

- (void)download:(NSURLDownload *)download didReceiveResponse:(NSURLResponse *)response {
    // reset the progress, this might be called multiple times
    bytesReceived=0;
    // retain the response to use later
    [self setDownloadResponse:response];
}

- (void)download:(NSURLDownload *)download didReceiveDataOfLength:(unsigned)length {
    long long expectedLength=[downloadResponse expectedContentLength];
    bytesReceived = bytesReceived + length;
	
    if (expectedLength != NSURLResponseUnknownLength) {
        // if the expected content length is
        // available, display percent complete
        double percentComplete=(bytesReceived/(float)expectedLength)*100.0;
        NSLog(@"Percent complete - %f",percentComplete);
		[progThread1 setDoubleValue:percentComplete];
		
    } else {
        // if the expected content length is
        // unknown just log the progress
		
        NSLog(@"Bytes received - %d",bytesReceived);
    }
}

@end
